<template>
  <div class="data-form recommend-goods-form" v-loading.fullscreen.lock="loading">
    <el-form label-width="auto" size="medium">
      <el-form-item label="总店">
        <span v-if="type!=='add'">{{goodsForm.branchName}}</span>
        <el-select v-else filterable v-model="goodsForm.branchId" class="form-input" :disabled="inputLoading" @change="branchChange">
          <el-option v-for="branch in branchList" :key="branch.branchId" :value="branch.branchId" :label="branch.branchName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分店">
        <span v-if="type!=='add'">{{goodsForm.partnerName}}</span>
        <el-select v-else filterable clearable v-model="goodsForm.partnerId" class="form-input" :disabled="inputLoading" @change="partnerChange">
          <el-option v-for="partner in partnerList" :key="partner.id" :value="partner.id" :label="partner.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="推荐商品">
        <span v-if="type!=='add'">{{goodsForm.goodsName}}</span>
        <el-select v-else filterable v-model="goodsForm.goodsDefId" class="form-input" :disabled="inputLoading">
          <el-option v-for="item in goodsList" :key="item.id" :value="item.id" :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="推荐类型">
        <span v-if="type!=='add'">{{i18n.getMsg(`goods.recommendGoods.type.${goodsForm.activityTypeId}`)}}</span>
        <el-select v-else v-model="goodsForm.activityTypeId" class="form-input">
          <el-option v-for="item in typeList" :key="item.value" :value="item.value" :label="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <sys-date-time-picker v-model="goodsForm.startTime" class="form-input" type="hour"></sys-date-time-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <sys-date-time-picker v-model="goodsForm.endTime" class="form-input" type="hour"></sys-date-time-picker>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="goodsForm.status" class="form-input">
          <el-option v-for="item in statusList" :key="item.value" :value="item.value" :label="item.label">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div style="text-align:center">
      <el-button size="medium" type="primary" @click="saveGoods">
        <span v-if="type==='add'">新增</span>
        <span v-else>修改</span>
      </el-button>
    </div>
  </div>
</template>

<script>
  import RecommendGoodsForm from 'models/goods/recommendGoodsForm';

  import SysDateTimePicker from 'commonComponents/sysDateTimePicker';

  import PermissionApi from 'services/permissionApi';
  import GoodsApi from 'services/goodsApi';
  import RecommendGoodsApi from 'services/recommendGoodsApi';

  export default {
    props: {
      goods: {
        type: Object,
        default () {
          return null
        }
      },
      type: {
        type: String,
        default: 'add'
      },
      dropdownOption: {
        type: Object,
        default () {
          return {};
        }
      }
    },

    data() {
      let goodsForm;
      if (this.type === 'add') {
        goodsForm = new RecommendGoodsForm();
      } else {
        goodsForm = _.cloneDeep(this.goods);
      }
      return {
        loading: false,
        inputLoading: false,
        goodsForm,
        typeList: this.i18n.getDropDown('goods.recommendGoods.type', [4]),
        statusList: this.i18n.getDropDown('goods.recommendGoods.status', [1, 0]),
        branchList: [],
        partnerList: [],
        goodsList: []
      };
    },

    created() {
      if (this.type !== 'add') {
        return;
      }

      this.loading = true;
      Promise.all([this.setBranchList()]).then(() => {
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    methods: {
      setBranchList() {
        let dropdownOption = this.dropdownOption;
        let branchList = dropdownOption.branchList;
        if (branchList !== undefined) {
          this.branchList = branchList;
          return Promise.resolve(branchList);
        }

        return PermissionApi.getBranchList().then(branchList => {
          this.branchList = branchList;
          dropdownOption.branchList = branchList;
          return branchList;
        });
      },

      setPartnerList() {
        let branchId = this.goodsForm.branchId;
        if (branchId === '') {
          this.partnerList = [];
          return Promise.resolve([]);
        }

        return PermissionApi.getPartners(branchId).then(partnerList => {
          this.partnerList = partnerList;
          return partnerList;
        });
      },

      setGoodsList(type) {
        return RecommendGoodsApi.getGoodsDropdown(this.goodsForm, type).then(goodsList => {
          let id = this.goodsForm.goodsDefId;
          let goods = _.find(goodsList, {
            id: id
          });
          if (goods === undefined) {
            this.goodsForm.goodsDefId = '';
          }

          this.goodsList = goodsList;
          return goodsList;
        });
      },

      branchChange() {
        this.inputLoading = true;
        Promise.all([
          this.setPartnerList(),
          this.setGoodsList('branch')
        ]).then(() => {
          this.activityForm.partnerId = '';
          this.inputLoading = false;
        }).catch(() => {
          this.inputLoading = false;
        });
      },

      partnerChange() {
        this.inputLoading = true;
        this.setGoodsList('partner').then(() => {
          this.inputLoading = false;
        }).catch(() => {
          this.inputLoading = false;
        });
      },

      saveGoods() {
        let goodsForm = this.goodsForm;
        let code = goodsForm.checkValid();
        if (code !== '') {
          let msg = this.i18n.getMsg(`goods.recommendGoods.error.${code}`);
          this.$message(msg);
          return;
        }

        if (this.type === 'add') {
          this.addGoods(goodsForm);
        } else {
          this.updateGoods(goodsForm);
        }
      },

      addGoods(goodsForm) {
        this.loading = true;
        RecommendGoodsApi.addRecommendGoods(goodsForm).then(() => {
          this.loading = false;
          this.$alert('推荐商品新增成功', '信息', {
            callback: () => {
              this.$emit('save-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      },

      updateGoods(goodsForm) {
        this.loading = true;
        RecommendGoodsApi.updateRecommendGoods(goodsForm).then(() => {
          this.loading = false;
          this.$alert('推荐商品修改成功', '信息', {
            callback: () => {
              this.$emit('save-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      }
    },

    components: {
      SysDateTimePicker
    }
  };

</script>

<style lang="scss" scoped>
  @import '~viewStyle/dataForm';

</style>
